<template>
  <div class="table-default">
    <el-button class="btn" type="primary" @click="goBack">返回</el-button>
    <el-button type="success" @click="submitForm(ruleFormRef, props.btnName)">{{ props.btnName }}</el-button>

    <el-form :model="form" label-width="100px" :inline="true" :rules="rules" ref="ruleFormRef">
      <el-form-item>
        <el-radio-group v-model="radioValue" style="padding-left: 10px" @change="changeSelect">
          <el-radio label="1" border>单独方案</el-radio>
          <el-radio label="2" border>共用方案</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="物料编码" prop="productname" v-if="radioValue == '1'">
        <el-input v-model="form.productname"  />
        <!-- <el-select v-model="form.productname" style="width: 240px" allow-create filterable :reserve-keyword="true" clearable multiple collapse-tags collapse-tags-tooltip>
          <el-option v-for="item in materielList" :key="item.id" :label="item.fnumber" :value="item.id"></el-option>
        </el-select> -->
      </el-form-item>

      <el-form-item label="检验方式" required prop="completecheck">
        <el-select v-model="form.completecheck" placeholder="选择抽检方式">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-table :data="form.detailscheck_all" stripe border>
        <el-table-column prop="testitem" label="测试项目" width="180">
          <template #default="scope">
            <el-form-item :prop="'detailscheck_all.' + scope.$index + '.testitem'" :rules="rules.testitem">
              <el-input v-model="scope.row.testitem" name="testitem" clearable />
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column prop="testmethod" label="测试方法" width="180">
          <template #default="scope">
            <el-form-item :prop="'detailscheck_all.' + scope.$index + '.testmethod'" :rules="rules.testmethod">
              <el-input v-model="scope.row.testmethod" name="testmethod" clearable />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="teststandard" label="测试合格标准" width="200">
          <template #default="scope">
            <el-form-item :prop="'detailscheck_all.' + scope.$index + '.teststandard'" :rules="rules.teststandard">
              <el-input v-model="scope.row.teststandard" name="teststandard" clearable />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" width="180">
          <template #default="scope">
            <el-form-item :prop="'detailscheck_all.' + scope.$index + '.remarks'">
              <el-input v-model="scope.row.remarks" name="remarks" clearable />
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column prop="teststandard" label="操作" width="180">
          <template #default="scope">
            <el-button type="danger" @click="delHandler(scope.$index)" class="tableBtn">删除</el-button>
            <el-button type="warning" @click="addHandler" v-if="scope.$index == form.detailscheck_all.length - 1" class="tableBtn"> 新增行 </el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, computed, watch } from 'vue'
import http from '/admin/support/http'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { ArrowDownBold } from '@element-plus/icons-vue'
import storage from '/admin/utils/storage'

const route = useRoute()
const router = useRouter()
const props = defineProps({
  editData: Object,
  btnName: String,
})

const form = reactive({
  detailscheck_all: [
    {
      testitem: '',
      testmethod: '',
      teststandard: '',
      remarks: '',
    },
  ],
})
const ruleFormRef = ref<FormInstance>()

const radioValue = ref('1')
let changeSelect = val => {
  console.log(val)
  // if (val == '2') {
  form.productname = []
  // }
}

const options = ref([
  {
    value: '0',
    label: '抽检',
  },
  {
    value: '1',
    label: '全检',
  },
])

let materielList = ref(storage.getItem('materielList'))

console.log('物料编码', materielList.value)


const rules = reactive({
  productname: [{ required: true, trigger: 'blur', message: '请输入产品名称' }],
  testitem: [{ required: true, message: '不能为空', trigger: 'blur' }],
  testmethod: [{ required: true, message: '不能为空', trigger: 'blur' }],
  teststandard: [{ required: true, message: '不能为空', trigger: 'blur' }],
  completecheck: [{ required: true, message: '不能为空', trigger: 'blur' }],
})

// console.log('触发create')

if (props.btnName == '确认编辑') {
  console.log(props.editData.productname)
  let currentCroductname = []
  if (props.editData.productname == '共用方案') {
    currentCroductname = []
  } else {
    materielList.value.map(item => {
      if (item.fnumber == props.editData.productname[0]) {
        return item.id
      }
    })
    let  list = materielList.value.filter(item => item.fnumber == props.editData.productname[0])
    currentCroductname = [list[0].id]
  }

  console.log(currentCroductname[0])
  console.log(currentCroductname[0].id)
  // form.productname = props.editData.productname
  form.productname = currentCroductname
  form.completecheck = String(props.editData.completecheck)
  // console.log(props.editData.detailscheck_all);
  props.editData.detailscheck_all.forEach((item, index) => {
    let obj = {}
    obj.testitem = item.testitem
    obj.testmethod = item.testmethod
    obj.teststandard = item.teststandard
    obj.remarks = item.remarks
    // detailscheck_all.value[index] = obj
    form.detailscheck_all[index] = obj
  })

  // console.log(detailscheck_all.value)
}

const selectedValue = ref(props.editData.completecheck)

const addHandler = () => {
  let obj = {
    testitem: '',
    testmethod: '',
    teststandard: '',
    remarks: '',
  }
  form.detailscheck_all.push(obj)
}

const delHandler = index => {
  form.detailscheck_all.splice(index, 1)
}

const submitForm = async (formEl: FormInstance | undefined, name) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (name == '保存新增') {
        console.log('新增表单内容：', form)
        http.post('/inspection/inspection', form).then(r => {
          if (r.data.code == '10000') {
            ElMessage({
              message: r.data.message,
              type: 'success',
            })
            ElMessage.success('即将跳转列表页')
            setTimeout(() => {
              goBack()
            }, 1000)
          } else {
            ElMessage({
              message: r.data.message,
              type: 'error',
            })
          }
        })
      }

      if (name == '确认编辑') {
        console.log('编辑表单内容：', form)

        http.put(`/inspection/inspection/${props.editData.id}`, form).then(r => {
          if (r.data.code == '10000') {
            ElMessage({
              message: r.data.message,
              type: 'success',
            })
            ElMessage.success('即将跳转列表页')
            setTimeout(() => {
              goBack()
            }, 1000)
          } else {
            ElMessage({
              message: r.data.message,
              type: 'error',
            })
          }
        })
      }
    } else {
      ElMessage({
        message: '请输入正确内容格式',
        type: 'warning',
      })
    }
  })
}

const emit = defineEmits(['send-data'])

const goBack = () => {
  console.log('触发goback')
  emit('send-data')
}
onMounted(() => {})
</script>


<style>
.rowone {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}
.addBtn {
  margin-left: 10px;
}
.btn {
  margin: 10px;
}
.all {
  width: 100%;
}
.el-form-item__content {
  margin-left: 0 !important;
}

.newBtn {
  margin: 30px 20px 0;
}
.tableBtn {
  margin-bottom: 20px;
}
</style>